<script setup>
import api from '../../api/goods_api.js'
import {ref, onMounted} from "vue";
import {ElMessageBox} from "element-plus";
import lodash from 'lodash'

//定义绑定的数据
//表格中的数据
const tableData = ref([]);
const total=ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
const addWinVisible=ref(false);

//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  name: '',
  title: '',
  category: '',
  image: '',
  origin: '',
  detail: '',
  price: '',
  stock: '',
  status: '',
  create_time: '',
  update_time: '',
  is_del: '',
});

//要修改或者新增的数据
const obj = ref({});
const search = async () => {
  try {
    console.log('发送的查询参数:', searchObj.value);
    var result = await api.getGoodsPage(searchObj.value.current, searchObj.value.limit, searchObj.value);
    console.log('收到的响应数据:', result);
    // 从 Result 对象中提取分页数据
    tableData.value = result.records;
    total.value = result.total;
  } catch (error) {
    console.error('获取商品列表时出错:', error);
    tableData.value = [];
    total.value = 0;
  }
}

//页面加载后要挂载的数据
onMounted(async () => {
  await search();
});

//重置查询条件
const resetSearch = () => {
  searchObj.value.name = '';
  searchObj.value.category = '';
  searchObj.value.current = 1;
  search();
}

//上传成功
const handleUploadSuccess = (response,file) => {
  console.log("-----------------");
  console.log(response);
  console.log(file);
  obj.value.image=response.data;
}
//分页查询用
const handleSizeChange=()=>{
  search();
}
//分页查询用
const handleCurrentChange=()=>{
  search();
}
//定义方法
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}
const handlerAdd=()=>{//添加
  obj.value={};
  addWinVisible.value=true;//打开对话框
}
//新增对话框的取消按钮点击事件
const addCancel=()=>{
  obj.value={};//清空数据
  addWinVisible.value=false;//关闭新增对话框
}
//编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}
//编辑对话框的提交按钮点击事件
const editCommit = async () => {
  await api.updateGoods(obj.value);//提交修改数据
  await search();//刷新表格
  editWinVisible.value = false;//关闭编辑对话框
}
//新增对话框的提交按钮点击事件
const addCommit=async()=>{
  await api.addGoods(obj.value);//提交新增数据
  await search();//刷新表格
  addWinVisible.value=false;//关闭新增对话框
}
const handleEdit = (index, row) => {
  obj.value=lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async() => {
        await api.deleteGoods(row.id);
        //重新加载数据
        //设置从第一页开始查询
        searchObj.value.current = 1;
        await search();
      })
      .catch(() => {
      })
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return dateTimeStr.replace('T', ' ');
}

// 切换商品状态
const handleStatusChange = async (row) => {
  await api.reverseStatus(row.id);
  await search(); // 刷新表格
}
</script>

<template>
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
    <el-form-item label="商品名称">
      <el-input v-model="searchObj.name" placeholder="请输入商品名称" clearable />
    </el-form-item>
    <el-form-item label="商品分类">
      <el-input v-model="searchObj.category" placeholder="请输入商品分类" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="resetSearch">重置</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerAdd">新增</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="商品ID" ></el-table-column>
    <el-table-column prop="name" label="商品名称"></el-table-column>
    <el-table-column prop="title" label="商品标题"></el-table-column>
    <el-table-column prop="category" label="商品分类"></el-table-column>
    <el-table-column prop="image" label="商品图片">
      <template #default="scope">
        <el-image
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            style="width: 40px; height: 40px; object-fit: cover;"
            fit="cover"
            alt="商品图片"
        /></template>
    </el-table-column>
    <el-table-column prop="price" label="商品价格"></el-table-column>
    <el-table-column prop="stock" label="库存数量"></el-table-column>
    <el-table-column prop="status" label="状态">
      <template #default="scope">
        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
          {{ scope.row.status === 1 ? '正常' : '下架' }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="create_time" label="创建时间">
      <template #default="scope">
        <span>{{ formatDateTime(scope.row.create_time) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="update_time" label="更新时间">
      <template #default="scope">
        <span>{{ formatDateTime(scope.row.update_time) }}</span>
      </template>
    </el-table-column>
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            :type="scope.row.status === 1 ? 'danger' : 'success'"
            @click="handleStatusChange(scope.row)"
        >
          {{ scope.row.status === 1 ? '下架' : '上架' }}
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10,20,30,50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!--编辑对话框-->
  <el-dialog v-model="editWinVisible" title="编辑商品" width="500">
    <el-form :model="obj">
      <el-form-item label="商品名称" :label-width="100">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品标题" :label-width="100">
        <el-input v-model="obj.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品分类" :label-width="100">
        <el-input v-model="obj.category" autocomplete="off" />
      </el-form-item>
      <el-form-item label="发货地" :label-width="100">
        <el-input v-model="obj.origin" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品详情" :label-width="100">
        <el-input v-model="obj.detail" type="textarea" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品价格" :label-width="100">
        <el-input v-model.number="obj.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="库存数量" :label-width="100">
        <el-input v-model.number="obj.stock" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品图片" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/user/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img  v-if="obj.image" :src="obj.image"  style="width:100px" />
          <img  v-else src='@/assets/upload.png'  style="width:100px"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态" :label-width="100">
        <el-radio-group v-model="obj.status">
          <el-radio :label="0">下架</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--新增对话框-->
  <el-dialog v-model="addWinVisible" title="新增商品" width="500">
    <el-form :model="obj">
      <el-form-item label="商品名称" :label-width="100">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品标题" :label-width="100">
        <el-input v-model="obj.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品分类" :label-width="100">
        <el-input v-model="obj.category" autocomplete="off" />
      </el-form-item>
      <el-form-item label="发货地" :label-width="100">
        <el-input v-model="obj.origin" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品详情" :label-width="100">
        <el-input v-model="obj.detail" type="textarea" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品价格" :label-width="100">
        <el-input v-model.number="obj.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="库存数量" :label-width="100">
        <el-input v-model.number="obj.stock" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品图片" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/user/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img  v-if="obj.image" :src="obj.image"  style="width:100px" />
          <img  v-else src='@/assets/upload.png'  style="width:100px"/>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
